'use strict';

exports.main = async (event, context) => {
	const db = uniCloud.database();
	const _ = db.command;
	const { taskData } = event;
	
	try {
		console.log('【addTask】开始创建任务:', taskData);
		
		// 写入 taskList 集合
		const res = await db.collection('taskList').add(taskData);
		console.log('【addTask】任务创建成功:', res.id);
		
		// 创建任务收入记录
		if (taskData.reward && taskData.reward > 0) {
			// 计算基础发布费（根据任务类型）
			let baseFee = 3; // 默认基础费
			if (taskData.type === 'delivery' || taskData.type === 'express') baseFee = 5;
			else if (taskData.type === 'purchase') baseFee = 4;
			else if (taskData.type === 'takeout') baseFee = 2;
			else if (taskData.type === 'other') baseFee = 3;
			
			// 计算总费用（悬赏 + 基础费）
			const totalAmount = taskData.reward + baseFee;
			
			console.log('【addTask】创建收入记录:', {
				taskId: res.id,
				publisherId: taskData.publisher_id,
				rewardAmount: taskData.reward,
				baseFee: baseFee,
				totalAmount: totalAmount
			});
			
			const incomeRecord = await db.collection('task_income_records').add({
				task_id: res.id, // 使用真实的任务ID
				publisher_id: taskData.publisher_id,
				reward_amount: taskData.reward, // 悬赏金额
				base_fee: baseFee,
				total_amount: totalAmount,
				status: 'pending',
				create_time: Date.now(),
				desc: '任务发布，等待接单者完成'
			});
			
			console.log('【addTask】收入记录创建成功:', incomeRecord.id);
		}
		
		// 发布成功后，调用积分管理云函数
		try {
			await uniCloud.callFunction({
				name: 'scoreManager',
				data: {
					action: 'post_create',
					userId: taskData.publisher_id,
					data: {
						postId: res.id
					}
				}
			})
		} catch (scoreError) {
			console.error('【addTask】积分计算失败:', scoreError)
		}
		
		return { code: 200, msg: '任务发布成功', data: res };
	} catch (e) {
		console.error('【addTask】任务发布失败:', e);
		return { code: 500, msg: '任务发布失败', error: e };
	}
};